// profile/index.ts
import { getRandomImage } from '../../utils/util';

interface ImageItem {
  id: string;
  prompt: string;
  imageUrl: string;
  height?: number; // 高度可选，将由图片加载后的实际高度决定
  createdAt: number;
}

// 扩展微信UserInfo类型，添加云数据库相关字段
interface CloudUserInfo extends WechatMiniprogram.UserInfo {
  _id?: string;
  openId?: string;
  createTime?: Date;
  lastLoginTime?: Date;
  imageCount?: number;
}

Page({
  data: {
    isLoggedIn: false,
    userInfo: null as CloudUserInfo | null,
    userImages: [] as ImageItem[],
    leftColumn: [] as ImageItem[],
    rightColumn: [] as ImageItem[],
    imageCount: 0,
    isLoading: false, // 添加加载状态标志
    lastLoadTime: 0 // 添加上次加载时间
  },

  onLoad() {
    this.checkLoginStatus();
  },

  onShow() {
    if (this.data.isLoggedIn) {
      const now = Date.now();
      // 如果距离上次加载时间超过5秒或首次加载，才重新加载图片
      if (now - this.data.lastLoadTime > 5000 || this.data.lastLoadTime === 0) {
        this.loadUserImages();
      }
    }
  },

  checkLoginStatus() {
    const app = getApp<{
      globalData: {
        userInfo: CloudUserInfo | null;
        isLoggedIn: boolean;
      };
    }>();
    
    if (app.globalData.isLoggedIn && app.globalData.userInfo) {
      this.setData({
        isLoggedIn: true,
        userInfo: app.globalData.userInfo
      });
      
      this.loadUserImages();
    }
  },

  async onGetUserInfo(e: any) {
    if (e.detail.userInfo) {
      const userInfo = e.detail.userInfo;
      
      // 显示加载状态
      wx.showLoading({
        title: '登录中...',
      });
      
      try {
        // 调用登录云函数，将用户信息保存到数据库
        const loginResult = await wx.cloud.callFunction({
          name: 'login',
          data: {
            userInfo: userInfo
          }
        });
        
        // @ts-ignore
        if (loginResult.result && loginResult.result.success) {
          // @ts-ignore
          const dbUserInfo = loginResult.result.userInfo as CloudUserInfo;
          
          // Save to global app data
          const app = getApp<{
            globalData: {
              userInfo: CloudUserInfo;
              hasUserInfo: boolean;
              isLoggedIn: boolean;
            };
          }>();
          
          app.globalData.userInfo = dbUserInfo;
          app.globalData.hasUserInfo = true;
          app.globalData.isLoggedIn = true;
          
          // Save to local storage for persistence
          wx.setStorageSync('userInfo', dbUserInfo);
          
          // Update page data
          this.setData({
            isLoggedIn: true,
            userInfo: dbUserInfo
          });
          
          // Load user images after login
          this.loadUserImages();
          
          // Show success toast
          wx.hideLoading();
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '登录失败',
            icon: 'error'
          });
          console.error('Login failed', loginResult);
        }
      } catch (err) {
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'error'
        });
        console.error('Login error', err);
      }
    }
  },

  onChangeAvatar() {
    // 打开相册选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        wx.showLoading({ title: '上传中...' });
        const tempFilePath = res.tempFilePaths[0];
        
        // 获取用户ID作为文件名
        const userId = this.data.userInfo?._id || 'unknown';
        
        // 上传图片到云存储
        const cloudPath = `user-avatars/${userId}_${new Date().getTime()}.jpg`;
        
        wx.cloud.uploadFile({
          cloudPath,
          filePath: tempFilePath,
          success: async (result) => {
            try {
              // 获取图片的访问地址
              const fileID = result.fileID;
              
              // 更新用户信息 - 调用login云函数
              const updateResult = await wx.cloud.callFunction({
                name: 'login',
                data: {
                  userInfo: {
                    ...this.data.userInfo,
                    avatarUrl: fileID,
                  }
                }
              });
              
              // @ts-ignore
              if (updateResult.result && updateResult.result.success) {
                // @ts-ignore
                const updatedUser = updateResult.result.userInfo as CloudUserInfo;
                
                // 更新全局状态和页面状态
                const app = getApp<{
                  globalData: {
                    userInfo: CloudUserInfo;
                  };
                }>();
                
                app.globalData.userInfo = updatedUser;
                wx.setStorageSync('userInfo', updatedUser);
                
                this.setData({
                  userInfo: updatedUser
                });
                
                wx.hideLoading();
                wx.showToast({
                  title: '头像更新成功',
                  icon: 'success'
                });
              } else {
                throw new Error('更新用户信息失败');
              }
            } catch (err) {
              console.error('更新头像失败', err);
              wx.hideLoading();
              wx.showToast({
                title: '更新失败',
                icon: 'error'
              });
            }
          },
          fail: (err) => {
            console.error('上传头像失败', err);
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'error'
            });
          }
        });
      }
    });
  },
  
  onEditProfile() {
    wx.showModal({
      title: '编辑个人资料',
      editable: true,
      placeholderText: this.data.userInfo?.nickName || '',
      content: this.data.userInfo?.nickName || '',
      success: async (res) => {
        if (res.confirm && res.content && res.content.trim()) {
          const newNickName = res.content.trim();
          
          // 如果名称没变，不执行更新
          if (newNickName === this.data.userInfo?.nickName) {
            return;
          }
          
          wx.showLoading({ title: '更新中...' });
          
          try {
            // 更新用户信息 - 调用login云函数
            const updateResult = await wx.cloud.callFunction({
              name: 'login',
              data: {
                userInfo: {
                  ...this.data.userInfo,
                  nickName: newNickName,
                }
              }
            });
            
            // @ts-ignore
            if (updateResult.result && updateResult.result.success) {
              // @ts-ignore
              const updatedUser = updateResult.result.userInfo as CloudUserInfo;
              
              // 更新全局状态和页面状态
              const app = getApp<{
                globalData: {
                  userInfo: CloudUserInfo;
                };
              }>();
              
              app.globalData.userInfo = updatedUser;
              wx.setStorageSync('userInfo', updatedUser);
              
              this.setData({
                userInfo: updatedUser
              });
              
              wx.hideLoading();
              wx.showToast({
                title: '昵称更新成功',
                icon: 'success'
              });
            } else {
              throw new Error('更新用户信息失败');
            }
          } catch (err) {
            console.error('更新昵称失败', err);
            wx.hideLoading();
            wx.showToast({
              title: '更新失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  loadUserImages() {
    // 检查是否正在加载中，避免重复请求
    if (this.data.isLoading) {
      return;
    }

    // 记录此次加载时间
    this.setData({
      isLoading: true,
      lastLoadTime: Date.now()
    });
    
    // 清空现有列数据
    this.setData({
      leftColumn: [],
      rightColumn: [],
      userImages: []
    });
    
    if (!this.data.userInfo || !this.data.userInfo._id) {
      this.setData({ isLoading: false });
      return;
    }
    
    wx.showLoading({
      title: '加载中',
    });
    
    // 查询用户创建的图片
    const db = wx.cloud.database();
    db.collection('images')
      .where({
        userId: this.data.userInfo._id
      })
      .orderBy('createdAt', 'desc')
      .get()
      .then(res => {
        wx.hideLoading();
        
        // 确保移除重复图片 (基于ID)
        const uniqueImagesMap = new Map();
        res.data.forEach((item: any) => {
          if (!uniqueImagesMap.has(item._id)) {
            uniqueImagesMap.set(item._id, {
              id: item._id,
              prompt: item.prompt,
              imageUrl: item.imageUrl,
              createdAt: item.createdAt ? new Date(item.createdAt).getTime() : Date.now()
            });
          }
        });
        
        const images = Array.from(uniqueImagesMap.values());
        
        // 按创建时间排序 (最新的在前面)
        images.sort((a, b) => b.createdAt - a.createdAt);
        
        console.log('用户图片加载完成，共', images.length, '张');
        
        this.setData({
          userImages: images,
          imageCount: images.length,
          isLoading: false
        });
        
        // 重新分配到两列
        this.setData({
          leftColumn: [],
          rightColumn: []
        });
        
        // 将图片分配到两列
        this.distributeImagesToColumns(images);
      })
      .catch(err => {
        console.error('获取用户图片失败', err);
        wx.hideLoading();
        
        // 重置加载状态
        this.setData({
          isLoading: false
        });
        
        // 尝试自动创建集合，然后再次尝试获取
        wx.cloud.callFunction({
          name: 'imageGenerator',
          data: {
            action: 'createImageTask',
            data: {
              _autoCreateCollection: true
            }
          },
          success: () => {
            console.log('尝试自动创建集合成功');
            // 延迟一点再重新加载，避免立即重试
            setTimeout(() => {
              // 重新加载用户图片
              this.loadUserImages();
            }, 1000);
          },
          fail: () => {
            console.error('尝试自动创建集合失败');
            // 如果获取失败，使用空数组
            this.setData({
              userImages: [],
              imageCount: 0
            });
          }
        });
      });
  },

  // 将图片分配到左右两列
  distributeImagesToColumns(images: ImageItem[]) {
    console.log('开始分配图片到两列，图片数量:', images.length);
    
    // 清空现有列
    this.setData({
      leftColumn: [],
      rightColumn: []
    });
    
    // 将新图片依次添加到较短的列
    images.forEach(image => {
      this.addItemToShortestColumn(image);
    });
  },
  
  // 将单个图片添加到较短的列
  addItemToShortestColumn(image: ImageItem, addToTop: boolean = false) {
    const { leftColumn, rightColumn } = this.data;
    
    // 决定放到哪一列（优先放到元素较少的列，以保持平衡）
    if (leftColumn.length <= rightColumn.length) {
      this.setData({
        leftColumn: addToTop ? [image, ...leftColumn] : [...leftColumn, image]
      });
    } else {
      this.setData({
        rightColumn: addToTop ? [image, ...rightColumn] : [...rightColumn, image]
      });
    }
  },
  
  // 监听图片加载完成事件
  onImageLoad(e: any) {
    // 可以用于记录图片的实际宽高比，如果需要的话
    // console.log('Image loaded', e.detail);
  },

  getMockUserImages(): ImageItem[] {
    // This would be replaced with actual API data
    const count = Math.floor(Math.random() * 6) + 3; // 3-8 images
    
    return Array.from({ length: count }, (_, i) => {
      const id = String(i + 1);
      return {
        id,
        prompt: `我的AI创作 #${id}`,
        imageUrl: getRandomImage(`user${id}`),
        createdAt: Date.now() - i * 86400000 // 1 day ago, 2 days ago, etc.
      };
    });
  },

  onCreateImage() {
    wx.navigateTo({
      url: '/pages/createImage/index'
    });
  },
  
  // 点击图片，跳转到详情页
  onImageTap(e: any) {
    const image = e.currentTarget.dataset.image;
    if (!image || !image.id) return;
    
    console.log('Profile page - Image tapped:', image);
    
    // 添加用户信息到图片对象
    const imageWithUser = {
      ...image,
      user: {
        nickName: this.data.userInfo?.nickName || '未知用户',
        avatarUrl: this.data.userInfo?.avatarUrl || ''
      }
    };
    
    wx.navigateTo({
      url: `/pages/imageDetail/index?id=${image.id}`,
      success: (res) => {
        // 将完整的图片数据传递给详情页
        res.eventChannel.emit('passImageData', { image: imageWithUser });
      }
    });
  }
}); 